library(export)

# setwd("D:/Work/Report/Plot")
source("X28_plot_functions.R")

path <- "D:/Work/TF/Ph1" # for working computer
datafile <- "XNW28012_SubjectList.xlsx"

#' Save plots to figure
#' @param note: the note of the plot
#' @param type: "png", "svg"
save_plots_figure <- function(note, type = "png") {
  # type: "png", "svg"
  type <- tolower(type)
  if (type == "svg") {
    type <- "svg"
  } else {
    type <- "png"
  }

  if (exists("pswim")) {
    filename <- paste0(
      "./Figures/",
      note,
      "_Swimmer_",
      format(Sys.Date(), "%Y%m%d"),
      ".",
      type
    )
    ggsave(
      paste0(filename),
      plot = pswim,
      width = 10,
      height = 6,
      dpi = "print",
      device = type
    )
    print("Swimming plot saved.")
  }

  if (exists("pspider")) {
    filename <- paste0(
      "./Figures/",
      note,
      "_Spider_",
      format(Sys.Date(), "%Y%m%d"),
      ".",
      type
    )
    ggsave(
      paste0(filename),
      plot = pspider,
      width = 8,
      height = 6,
      dpi = "print",
      device = type
    )
    print("Spider plot saved.")
  }

  if (exists("pwaterfall")) {
    filename <- paste0(
      "./Figures/",
      note,
      "_Waterfall_",
      format(Sys.Date(), "%Y%m%d"),
      ".",
      type
    )
    ggsave(
      paste0(filename),
      plot = pwaterfall,
      width = 8,
      height = 6,
      dpi = "print",
      device = type
    )
    print("Waterfall plot saved.")
  }
}


#' Save plots to ppt
save_plots_ppt <- function() {
  filename <- paste0(
    "./Figures/X28_plots_",
    format(Sys.Date(), "%Y%m%d"),
    ".pptx"
  )
  if (exists("pswim")) {
    graph2ppt(x = pswim, file = filename, width = 10, height = 6, append = TRUE)
    print("Swimming plot saved.")
  }

  if (exists("pspider")) {
    graph2ppt(
      x = pspider,
      file = filename,
      width = 8,
      height = 6,
      append = TRUE
    )
    print("Spider plot saved.")
  }

  if (exists("pwaterfall")) {
    graph2ppt(
      x = pwaterfall,
      file = filename,
      width = 8,
      height = 6,
      append = TRUE
    )
    print("Waterfall plot saved.")
  }
}


#' Save plots
#' @param note: the note of the plot
#' @param save.type: the type of the plot
save_plots <- function(note, save.type = "PPT") {
  if (save.type == "PPT") {
    save_plots_ppt()
  } else if (save.type == "PNG") {
    save_plots_figure(note = note, type = "png")
  } else if (save.type == "SVG") {
    save_plots_figure(note = note, type = "svg")
  }
}
